package com.hacpai.android.md.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hacpai.android.md.model.entity.Article;
import com.hacpai.android.md.model.entity.Domain;
import com.hacpai.android.md.presenter.implement.MainPresenter;
import com.hacpai.android.md.ui.adapter.DomainListAdapter;
import com.hacpai.android.md.ui.fragment.SlidingTabsColorsFragment;
import com.hacpai.android.md.ui.widget.ListView;

import com.hacpai.android.md.R;
import com.hacpai.android.md.model.entity.TabType;
import com.hacpai.android.md.model.storage.LoginShared;
import com.hacpai.android.md.model.storage.SettingShared;
import com.hacpai.android.md.presenter.contract.IMainPresenter;

import com.hacpai.android.md.ui.base.FullLayoutActivity;
import com.hacpai.android.md.ui.dialog.AlertDialogUtils;
import com.hacpai.android.md.ui.listener.DoubleClickBackToContentTopListener;
import com.hacpai.android.md.ui.listener.NavigationOpenClickListener;
import com.hacpai.android.md.ui.util.Navigator;
import com.hacpai.android.md.ui.util.ThemeUtils;
import com.hacpai.android.md.ui.util.ToastUtils;
import com.hacpai.android.md.ui.view.IBackToContentTopView;
import com.hacpai.android.md.ui.view.IMainView;
import com.hacpai.android.md.ui.viewholder.LoadMoreFooter;
import com.hacpai.android.md.util.FormatUtils;
import com.hacpai.android.md.util.HandlerUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends FullLayoutActivity implements IMainView,IBackToContentTopView{

    // 抽屉导航布局
    @BindView(R.id.drawer_layout)
    protected DrawerLayout drawerLayout;

    // 导航部分的个人信息
    @BindView(R.id.img_avatar)
    protected ImageView imgAvatar;

    @BindView(R.id.tv_login_name)
    protected TextView tvLoginName;

    @BindView(R.id.tv_score)
    protected TextView tvScore;

    @BindView(R.id.badge_nav_notification)
    protected TextView tvBadgeNotification;

    @BindView(R.id.btn_logout)
    protected View btnLogout;

    @BindView(R.id.btn_theme_dark)
    protected ImageView imgThemeDark;

    @BindView(R.id.img_nav_top_background)
    protected ImageView imgTopBackground;

    @BindView(R.id.ls_domains)
    protected ListView ls_domains;


    protected List<CheckedTextView> navMainItemList;

    // 内容部分
    @BindView(R.id.toolbar)
    protected Toolbar toolbar;

    // 首次按下返回键时间戳
    private long firstBackPressedTime = 0;

    // 是否启用夜间模式
    private boolean enableThemeDark;

    private IMainPresenter mainPresenter;
    private DomainListAdapter domainListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        enableThemeDark = ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight_FitsStatusBar, R.style.AppThemeDark_FitsStatusBar);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);

        if (savedInstanceState == null) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            SlidingTabsColorsFragment fragment = new SlidingTabsColorsFragment();
            transaction.replace(R.id.sample_content_fragment, fragment);
            transaction.commit();
        }

        drawerLayout.setDrawerShadow(R.drawable.navigation_drawer_shadow, GravityCompat.START);
        drawerLayout.addDrawerListener(drawerListener);

        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new NavigationOpenClickListener(drawerLayout));
        toolbar.setOnClickListener(new DoubleClickBackToContentTopListener(this));
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.action_search) {
                    //TODO
                } else if (item.getItemId() == R.id.action_message) {
                    //TODO
                }
                return true;
            }
        });

        mainPresenter = new MainPresenter(this, this);
        domainListAdapter = new DomainListAdapter(this);
        ls_domains.setAdapter(domainListAdapter);


        updateUserInfoViews();

        imgThemeDark.setImageResource(enableThemeDark ? R.drawable.ic_wb_sunny_white_24dp : R.drawable.ic_brightness_3_white_24dp);
        imgTopBackground.setVisibility(enableThemeDark ? View.INVISIBLE : View.VISIBLE);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }



    @Override
    protected void onResume() {
        super.onResume();
        // 判断是否需要切换主题
        if (SettingShared.isEnableThemeDark(this) != enableThemeDark) {
            ThemeUtils.notifyThemeApply(this, true);
        }
    }

    private final DrawerLayout.DrawerListener drawerListener = new DrawerLayout.SimpleDrawerListener() {

        @Override
        public void onDrawerOpened(View drawerView) {
            updateUserInfoViews();
            mainPresenter.getDomains();
//            mainPresenter.getMessageCountAsyncTask();
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            TabType tab = TabType.all;
//            for (CheckedTextView navItem : navMainItemList) {
//                if (navItem.isChecked()) {
//                    switch (navItem.getId()) {
//
//                        default:
//                            throw new AssertionError("Unknow tab.");
//                    }
//
//                }
//            }
           mainPresenter.switchTab(tab);
        }

    };




    public void onNavigationMainItemClick(CheckedTextView itemView) {
        for (CheckedTextView navItem : navMainItemList) {
            navItem.setChecked(navItem.getId() == itemView.getId());
        }
        drawerLayout.closeDrawers();
    }

    /**
     * 次要菜单导航
     */

    @OnClick({
            R.id.btn_nav_notification,
            R.id.btn_nav_setting,
            R.id.btn_nav_about
    })
    public void onNavigationItemOtherClick(View itemView) {
        switch (itemView.getId()) {
            case R.id.btn_nav_notification:
                if (LoginActivity.checkLogin(this)) {
                    notificationAction.startDelayed();
                    drawerLayout.closeDrawers();
                }
                break;
            case R.id.btn_nav_setting:
                settingAction.startDelayed();
                drawerLayout.closeDrawers();
                break;
            case R.id.btn_nav_about:
                aboutAction.startDelayed();
                drawerLayout.closeDrawers();
                break;
        }
    }

    private class OtherItemAction implements Runnable {

        private Class gotoClz;

        protected OtherItemAction(Class gotoClz) {
            this.gotoClz = gotoClz;
        }

        @Override
        public void run() {
            if (gotoClz == NotificationActivity.class) {
                Navigator.NotificationWithAutoCompat.start(MainActivity.this);
            } else {
                startActivity(new Intent(MainActivity.this, gotoClz));
            }
        }

        public void startDelayed() {
            HandlerUtils.postDelayed(this, 400);
        }

    }

    private OtherItemAction notificationAction = new OtherItemAction(NotificationActivity.class);
    private OtherItemAction settingAction = new OtherItemAction(SettingActivity.class);
    private OtherItemAction aboutAction = new OtherItemAction(AboutActivity.class);

    /**
     * 注销按钮
     */
    @OnClick(R.id.btn_logout)
    protected void onBtnLogoutClick() {
        AlertDialogUtils.createBuilderWithAutoTheme(this)
                .setMessage(R.string.logout_tip)
                .setPositiveButton(R.string.logout, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mainPresenter.logoutUser();
                    }

                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    @Override
    public void logoutUserOk() {
        LoginShared.logout(MainActivity.this);
        tvBadgeNotification.setText(null); // 未读消息清空
        updateUserInfoViews();
    }

    /**
     * 主题按钮
     */
    @OnClick(R.id.btn_theme_dark)
    protected void onBtnThemeDarkClick() {
        SettingShared.setEnableThemeDark(this, !enableThemeDark);
        ThemeUtils.notifyThemeApply(this, false);
    }

    /**
     * 用户信息按钮
     */
    @OnClick(R.id.layout_info)
    protected void onBtnInfoClick() {
        if (TextUtils.isEmpty(LoginShared.getToken(this))) {
            LoginActivity.startForResult(this);
        } else {
            UserDetailActivity.startWithTransitionAnimation(this, LoginShared.getLoginName(this), imgAvatar ,LoginShared.getAvatarUrl210(this));
        }
    }

    /**
     * 发帖按钮
     */
//    @OnClick(R.id.fab_create_topic)
//    protected void onBtnCreateTopicClick() {
//        if (LoginActivity.checkLogin(this)) {
//            startActivity(new Intent(this, CreateTopicActivity.class));
//        }
//    }

    /**
     * 判断登录是否成功
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LoginActivity.REQUEST_LOGIN && resultCode == RESULT_OK) {
            mainPresenter.getUserAsyncTask();
            updateUserInfoViews();
        }
    }

    /**
     * 返回键关闭导航
     */
    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            long secondBackPressedTime = System.currentTimeMillis();
            if (secondBackPressedTime - firstBackPressedTime > 2000) {
                ToastUtils.with(this).show(R.string.press_back_again_to_exit);
                firstBackPressedTime = secondBackPressedTime;
            } else {
                super.onBackPressed();
            }
        }
    }



    @Override
    public void updateUserInfoViews() {
        if (TextUtils.isEmpty(LoginShared.getToken(this))) {
            Glide.with(this).load(R.drawable.image_placeholder).placeholder(R.drawable.image_placeholder).dontAnimate().into(imgAvatar);
            tvLoginName.setText(R.string.click_avatar_to_login);
            tvScore.setText(null);
            btnLogout.setVisibility(View.GONE);
        } else {
            Glide.with(this).load(LoginShared.getAvatarUrl210(this))
                    .error(R.drawable.image_placeholder)
                    .placeholder(R.drawable.image_placeholder).dontAnimate().into(imgAvatar);
            tvLoginName.setText(LoginShared.getLoginName(this));
            tvScore.setText(getString(R.string.score_$d, LoginShared.getPoint(this)));
            btnLogout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void updateMessageCountViews(int count) {
        tvBadgeNotification.setText(FormatUtils.getNavigationDisplayCountString(count));
    }

    @Override
    public void updateDomains(@NonNull List<Domain> domains) {
        domainListAdapter.setDomainList(domains);
        domainListAdapter.notifyDataSetChanged();


        fixListViewHeight(ls_domains);
    }

    @Override
    public void backToContentTop() {
        //TODO
    }

    @Override
    public void onLoadMoreTopicListFinish(@LoadMoreFooter.State int state) {

    }

    @Override
    public void onLoadMoreTopicListOk(@NonNull List<Article> topicList) {

    }

    @Override
    public void onSwitchTabOk(@NonNull TabType tab) {

    }

    @Override
    public void onRefreshTopicListOk(@NonNull List<Article> topicList) {

    }

    @Override
    public void onRefreshTopicListFinish() {

    }


    /**
     * 解决listview和scollview的冲突
     * @param listView
     */
    private void fixListViewHeight(ListView listView) {
        // 如果没有设置数据适配器，则ListView没有子项，返回。
        ListAdapter listAdapter = listView.getAdapter();
        int totalHeight = 0;
        if (listAdapter == null) {
            return;
        }
        for (int index = 0, len = listAdapter.getCount(); index < len; index++) {
            View listViewItem = listAdapter.getView(index , null, listView);
            // 计算子项View 的宽高
            listViewItem.measure(0, 0);
            // 计算所有子项的高度和
            totalHeight += listViewItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // listView.getDividerHeight()获取子项间分隔符的高度
        // params.height设置ListView完全显示需要的高度
        params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}
